package cn.tedu.tmall.front.mall.service.impl;

import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import cn.tedu.tmall.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.tmall.common.pojo.vo.PageData;
import cn.tedu.tmall.front.mall.dao.cache.ICartCacheRepository;
import cn.tedu.tmall.front.mall.dao.cache.impl.CartCacheRepository;
import cn.tedu.tmall.front.mall.dao.persist.repository.IGoodsRepository;
import cn.tedu.tmall.front.mall.dao.persist.repository.IOrderRepository;
import cn.tedu.tmall.front.mall.dao.persist.repository.IReceiverAddressRepository;
import cn.tedu.tmall.front.mall.pojo.entity.Order;
import cn.tedu.tmall.front.mall.pojo.param.OrderAddNewParam;
import cn.tedu.tmall.front.mall.pojo.po.CartPO;
import cn.tedu.tmall.front.mall.pojo.vo.*;
import cn.tedu.tmall.front.mall.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.bridge.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class OrderService implements IOrderService {
    @Value("${tmall.dao.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    private IReceiverAddressRepository receiverAddressRepository;
    @Autowired
    private IGoodsRepository goodsRepository;
    @Autowired
    private ICartCacheRepository cartCacheRepository;
    @Autowired
    private IOrderRepository orderRepository;

    @Override
    public Long create(CurrentPrincipal currentPrincipal, OrderAddNewParam orderAddNewParam) {
        // 获取收货地址的id
        Long receiverAddressId = orderAddNewParam.getReceiverAddressId();
        // 根据ID查询用户的数据详情
        ReceiverAddressStandardVO receiverAddress = receiverAddressRepository.getStandardById(receiverAddressId);
        // 判断收货地址是否存在
        if (receiverAddress == null) {
            String message = "创建订单失败,收货地址不存在";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        // 判断是否是本人收货地址
        if (!receiverAddress.getUserId().equals(currentPrincipal.getId())) {
            String message = "创建订单失败,收货地址不存在";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        // 获取省市区详情地址
        String fullAddress = receiverAddress.getProvince()
                + receiverAddress.getCity()
                + receiverAddress.getArea()
                + receiverAddress.getDetail();

        // 获取商品id
        Long[] goodsIdList = orderAddNewParam.getGoodsIdList();

        BigDecimal totalPrice = BigDecimal.ZERO;
        Integer goodsTotalNum = 0;

        List<GoodsStandardVO> goodsList = new ArrayList<>();
        List<Integer> goodsNumList = new ArrayList<>();

        for (int i = 0; i < goodsIdList.length; i++) {
            GoodsStandardVO goods = goodsRepository.getStandardById(goodsIdList[i]);
            if (goods == null) {
                String message = "创建订单失败,部分商品不存在";
                throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
            }
            if (goods.getIsPutOn() != 1) {
                String message = "创建订单失败,商品未上架";
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }

            goodsList.add(goods);
            CartPO cartPO = cartCacheRepository.getByUserAndGoods(currentPrincipal.getId(), goodsIdList[i]);
            // 查询购物车中是否有该商品
            if (cartPO == null) {
                String message = "创建订单失败,购物车数据异常,请返回购物车并重新下单";
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);

            }

            Integer goodsNum = cartPO.getGoodsNum();
            goodsNumList.add(goodsNum);

            goodsTotalNum += goodsNum;

            BigDecimal salePrice = goods.getSalePrice();
            BigDecimal multiply = salePrice.multiply(new BigDecimal(goodsNum));
            totalPrice = totalPrice.add(multiply);
        }

        Order order = new Order();
        // UUID获取随机订单号
        order.setOrderNo(UUID.randomUUID().toString());
        // 根据当事人获取买家ID
        order.setBuyerId(currentPrincipal.getId());
        order.setBuyerUsername(currentPrincipal.getUsername());
        // 根据之前ID查询用户数据详情获取收件人名称
        order.setReceiverName(receiverAddress.getReceiverName());
        // 根据之前ID查询用户数据详情获取收件人手机号
        order.setReceiverPhone(receiverAddress.getReceiverPhone());
        // 根据之前ID查询用户数据详情获取收件人收货地址
        order.setReceiverAddress(fullAddress);
        // 获取商品数量
        order.setGoodsNum(goodsTotalNum);
        // 获取商品总价
        order.setTotalPrice(totalPrice);
        // 订单状态：待支付
        order.setOrderState(ORDER_STATE_UNPAID);
        int insert = orderRepository.insert(order);
        // 判断是否插入数据成功
        if (insert != 1) {
            String message = "创建订单失败,服务器繁忙";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        for (int i = 0; i < goodsIdList.length; i++) {
            cartCacheRepository.deleteByUserAndGoods(currentPrincipal.getId(), goodsIdList[i]);

        }
        return order.getId();
    }

    @Override
    public OrderStandardVO getStandardById(CurrentPrincipal currentPrincipal, Long orderId) {
        log.debug("开始处理根据id查询订单");
        OrderStandardVO order = orderRepository.getStandardByIdAndUser(orderId, currentPrincipal.getId());
        if (order == null) {
            String message = "查询订单失败,访问的数据不存在";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return order;
    }

    @Override
    public PageData<OrderListItemVO> listByUser(CurrentPrincipal currentPrincipal, Integer pageNum) {
        log.debug("开始处理查询订单列表业务");
        return orderRepository.listByUser(currentPrincipal.getId(), pageNum,defaultQueryPageSize);
    }
}
